package com.wushixin.springdemo.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wushixin.springdemo.dao.BookMapper;
import com.wushixin.springdemo.dto.BookDto;
import com.wushixin.springdemo.pojo.Book;
import com.wushixin.springdemo.pojo.TypeInfo;
import com.wushixin.springdemo.service.BookService;
import com.wushixin.springdemo.service.TypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    @Autowired
    private TypeService typeService;

    @Override
    public List<BookDto> getAll() {
        List<BookDto> bookDtos = new ArrayList<>();
        // 查询全部书籍
        List<Book> bookList = super.list();
        // 将全部书籍的值给bookdto
        BeanUtils.copyProperties(bookList,bookDtos);
        // 查询booktype
        for (BookDto bookDto : bookDtos) {
            // 将booktype的typeName赋值给每个bookdto
            TypeInfo typeInfo = typeService.getById(bookDto.getTypeId());
            bookDto.setTypeName(typeInfo.getName());
            bookDtos.add(bookDto);
        }
        // 返回
        return bookDtos;

    }

    @Override
    public Page<BookDto> getPage(Integer current, Integer pageSize, String name) {
        IPage<Book> bookpage = new Page<>(current,pageSize);
        LambdaQueryWrapper<Book> bookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        bookLambdaQueryWrapper.like(name!=null,Book::getName,name);
        this.page(bookpage,bookLambdaQueryWrapper);

        Page<BookDto> bookDtoPage = new Page<>();
        BeanUtils.copyProperties(bookpage,bookDtoPage,"records");

        List<Book> bookList = new ArrayList<>();
        List<BookDto> bookDtoList = new ArrayList<>();

        bookList = bookpage.getRecords();

        for (Book book : bookList) {
            BookDto bookDto = new BookDto();
            BeanUtils.copyProperties(book,bookDto);
            TypeInfo typeInfo = typeService.getById(book.getTypeId());
            bookDto.setTypeName(typeInfo.getName());
            bookDtoList.add(bookDto);
        }
        bookDtoPage.setRecords(bookDtoList);
        return bookDtoPage;
    }
}
